package com.droidnetrun.main;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.BasicResponseHandler;

import android.net.http.AndroidHttpClient;

public class PluginHttpClient {
	private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5";
	private static AndroidHttpClient httpClient = AndroidHttpClient.newInstance(USER_AGENT);

	public final static String downloadString(String resUrl) throws ClientProtocolException, IOException {
		try {
			HttpUriRequest request = new HttpGet(resUrl);
			String responseText = httpClient.execute(request, new BasicResponseHandler());
			return responseText;
		} finally {
//			httpClient.getConnectionManager().shutdown();
		}
	}

	public final static void downloadFile(String resUrl, String savePath) throws ClientProtocolException, IOException {
		try {
			HttpUriRequest request = new HttpGet(resUrl);
			HttpResponse response = httpClient.execute(request);
			InputStream in = response.getEntity().getContent();
			FileOutputStream out = null;
			try {
				out = new FileOutputStream(savePath);
				byte[] buffer = new byte[128];
				int len = -1;
				while ((len = in.read(buffer)) != -1) {
					out.write(buffer, 0, len);
				}
			} finally {
				if (null != out) {
					out.close();
				}
			}
		} finally {
//			httpClient.getConnectionManager().shutdown();
		}
	}

	public final static Properties downloadProperties(String resUrl) throws ClientProtocolException, IOException {
		try {
			HttpUriRequest request = new HttpGet(resUrl);
			HttpResponse response = httpClient.execute(request);
			Properties p = new Properties();
			p.load(response.getEntity().getContent());
			return p;
		} finally {
//			httpClient.getConnectionManager().shutdown();
		}
	}
}
